require('dotenv').config()
const robot = require('robotjs')

function main() {
    const size = robot.getScreenSize()
    openBottomMenu(size.width - 230, size.height - 20)
    openSunflowerClient(size.width - 245, size.height - 100)
    const isLogin = findColorInRegion(670, 400, 676, 404, '#FF7E00')
    if (!isLogin) {
        fillSunAccount()   // 未登录向日葵则执行登录向日葵
        console.log('===================登录向日葵!')
    }
    console.log('===================登录远程机!')
    connectBoard()         // 已登录向日葵则直接输入远程机
    console.log('===================执行完毕!')
}

/**
 * 1. 点击最底部折叠菜单
 */
function openBottomMenu(x, y) {
    robot.moveMouse(x, y)
    robot.mouseClick()
}

/**
 * 2. 点击向日葵
 */
function openSunflowerClient(x, y) {
    robot.moveMouse(x, y)
    robot.mouseClick('right')
    robot.moveMouse(x + 20, y - 135)
    robot.mouseClick()
}

/**
 * 3. 判断向日葵是否已登录账号
 * @param left
 * @param top
 * @param right
 * @param bottom
 * @param color
 */
function findColorInRegion(left, top, right, bottom, color) {
    for (let y = top; y < bottom; y++) {
        for (let x = left; x < right; x++) {
            const colorAtPixel = '#' + robot.screen.capture(x, y, 1, 1).colorAt(0, 0)
            if (colorAtPixel.toUpperCase() === color.toUpperCase()) {
                return {x, y}
            }
        }
    }
    return null
}

/**
 * 4. 根据3的结果：未登录则执行登录向日葵客户端
 */
function fillSunAccount() {
    robot.moveMouse(666, 436)
    robot.mouseClick()
    robot.moveMouse(1162, 468)
    robot.mouseClick()
    deleteAction(16)
    robot.typeString(process.env.SUN_USER_NAME)
    robot.moveMouse(1174, 512)
    robot.mouseClick()
    deleteAction(16)
    robot.typeString(process.env.SUN_PASSWORD)
    robot.moveMouse(1050, 600)
    robot.mouseClick()
}

/**
 * 5. 根据3的结果：登录则执行连接远程桌面
 */
function connectBoard() {
    robot.moveMouse(1248, 458)
    robot.mouseClick()
    deleteAction(12)
    robot.typeString(process.env.BOARD_HOST)
    robot.moveMouse(1280, 553)
    robot.mouseClick()
    deleteAction(12)
    robot.typeString(process.env.BOARD_CODE)
    robot.moveMouse(1215, 654)
    robot.mouseClick()
}

/**
 * 删除指定个数字符
 * @param count
 */
function deleteAction(count) {
    for (let i = 0; i < count; i++) {
        robot.keyTap('backspace');
    }
}

main()